package senpec.qc.harmony.system.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import senpec.qc.harmony.base.exception.NoResultException;
import senpec.qc.harmony.base.file.fileInfo.FileInfo;
import senpec.qc.harmony.base.file.fileInfo.FileInfoMapper;
import senpec.qc.harmony.base.mybatisplus.IBaseServiceImpl;
import senpec.qc.harmony.base.mybatisplus.Result;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends IBaseServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final FileInfoMapper fileInfoMapper;

    @Override
    public Result<User> getById(Long id) {
        User user = userMapper.selectById(id);
        System.out.println("user = " + user);
        return getUserResult(user);

    }

    private Result<User> getUserResult(User user) {
        if (user == null) {
            throw new NoResultException();
        } else {
            FileInfo fileInfo = fileInfoMapper.selectOneByKeyWord(user.getHeadImageUuid());
            if (fileInfo != null) {
                user.setHeadImageUrl(fileInfo.getUrl());
            }
            return Result.ok(user.toSafe());
        }
    }

    @Override
    public Result<List<User>> getListByConditions(User conditions) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<User> users = userMapper.selectList(lambdaQueryWrapper);
        users.forEach(item -> {
            FileInfo fileInfo = fileInfoMapper.selectOneByKeyWord(item.getHeadImageUuid());
            if (fileInfo != null) {
                item.setHeadImageUrl(fileInfo.getUrl());
            }
        });
        return Result.ok(users);
    }

    @Override
    public Result<User> getOneByCondition(String columnName, Object columnValue) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (columnName.equals("username")) {
            queryWrapper.eq(User::getUsername, columnValue);
        }
        User user = userMapper.selectOne(queryWrapper);
        return getUserResult(user);


    }

    @Override
    public Result<User> updateOne(User entity) {
        System.out.println(entity);
        try {
            setVersion(entity);
            int updated = userMapper.updateById(entity);
            if (updated > 0) {
                setCreatorAndUpdater(entity);
                return Result.ok(entity).msg("更新用户成功。");
            } else {
                return Result.error(entity).msg("更新用户失败。");
            }
        } catch (RuntimeException e) {
            return Result.error(entity).msg("更新用户失败，详细信息是，" + e.getMessage());
        }
    }
}